
import RedisDAO from "../../util/DAO/redis_dao";
import Queue from "../../util/queue";
import Player from "./player";




export default class PlayerDAO extends RedisDAO {
	private saveQueue: Queue<Player> = new Queue();
	private isSaving = false;

	private redisKeyOf(player: Player, attribute: string) {
		return `LNE:players:${player.qqNum}:${attribute}`;
	}
	private valueOf(player: Player, attribute: string): Promise<string> {
		return this.redis.get(this.redisKeyOf(player, attribute));
	}

	async loadPlayerById(id: number): Promise<Player> {
		let player = new Player();
		player.qqNum = id;
		await this.reloadPlayer(player);
		return player;
	}

	async reloadPlayer(player: Player) {
		player.coin = Number.parseInt(await this.valueOf(player, "coin"));
		player.nick = await this.valueOf(player, "nick");
		player.totalExp = Number.parseInt(await this.valueOf(player, "total_exp"));
		player.hpRatio = Number.parseFloat(await this.valueOf(player, "hp_ratio"));
	}

	async savePlayer(player: Player) {

	}

	savePlayerSync(player: Player) {
		this.saveQueue.enqueue(player);
		this.saveQueuePlayers().then(() => console.log("同步保存完毕"));
	}

	async saveQueuePlayers() {
		if (this.isSaving) return;
		this.isSaving = true;
		while (!this.saveQueue.isEmpty()) {
			await this.savePlayer(this.saveQueue.dequeue());
		}
		this.isSaving = false;
	}
}